package com.sansan.qiangji.realize.system;

import com.sansan.qiangji.VO.system.power.PowerListResultVO;
import com.sansan.qiangji.VO.system.power.PowerVO;
import com.sansan.qiangji.VO.system.role.RolePowerGroupVO;
import com.sansan.qiangji.VO.system.role.RolePowerVO;
import com.sansan.qiangji.VO.system.user.UserPowerGroupVO;
import com.sansan.qiangji.VO.system.user.UserPowerVO;
import com.sansan.qiangji.entity.system.Power;
import com.sansan.qiangji.entity.system.Role;
import com.sansan.qiangji.entity.system.User;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.system.power.PowerAddForm;
import com.sansan.qiangji.form.system.power.PowerEditForm;
import com.sansan.qiangji.form.system.power.PowerListForm;
import com.sansan.qiangji.service.impl.system.PowerServiceImpl;
import com.sansan.qiangji.service.impl.system.RoleServiceImpl;
import com.sansan.qiangji.service.impl.system.UserServiceImpl;
import com.sansan.qiangji.utils.pageUtils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PowerReal {
    private PowerServiceImpl powerService;
    private RoleServiceImpl roleService;
    private UserServiceImpl userService;

    @Resource
    public void setPowerService(PowerServiceImpl powerService) {
        this.powerService = powerService;
    }

    @Resource
    public void setRoleService(RoleServiceImpl roleService) {
        this.roleService = roleService;
    }

    @Resource
    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }

    @Transactional
    public void createPower(PowerAddForm powerAddForm) {
        List<Power> powers = powerService.findByPowerNameOrPowerPath(powerAddForm.getPowerName(), powerAddForm.getPowerPath());
        if (powers.size() != 0) {
            log.error("【创建权限】权限名或权限路径已存在，powerAddForm={}", powerAddForm);
            throw new ServiceException(ResultEnum.POWER_EXIST);
        }
        Power power = new Power();
        power.setPowerName(powerAddForm.getPowerName());
        power.setPowerPath(powerAddForm.getPowerPath());
        power.setPowerGroup(powerAddForm.getPowerGroup());
        StringBuilder powerAccessMethods = new StringBuilder();
        for (String powerAccessMethod : powerAddForm.getPowerAccessMethodList()) {
            if (powerAccessMethods.toString().equals("")) {
                powerAccessMethods = new StringBuilder(powerAccessMethod);
            } else {
                powerAccessMethods.append("||").append(powerAccessMethod);
            }
        }
        power.setPowerAccessMethod(powerAccessMethods.toString());
        power.setPowerStatus(true);
        powerService.addPower(power);
    }

    public PowerListResultVO getPowers(PowerListForm powerListForm) {
        PageResult<Power> pageResultPower = powerService.powerList(powerListForm);
        PowerListResultVO powerListResultVO = new PowerListResultVO();
        BeanUtils.copyProperties(pageResultPower, powerListResultVO);
        List<PowerVO> powerVOS = new ArrayList<>();
        for (Power power : pageResultPower.getContent()) {
            PowerVO powerVO = new PowerVO();
            BeanUtils.copyProperties(power, powerVO);
            powerVOS.add(powerVO);
        }
        powerListResultVO.setPowerVOS(powerVOS);
        return powerListResultVO;
    }

    @Transactional
    public void deletePower(Integer powerId) {
        Power power = powerService.findByPowerId(powerId);
        if (power == null) {
            log.error("【权限删除】权限不存在，powerId={}", powerId);
            throw new ServiceException(ResultEnum.POWER_NOT_EXIST);
        }
        int rows = powerService.deleteById(powerId);
        if (rows == 0) {
            log.error("【权限删除】权限删除失败，power={}", power.toString());
            throw new ServiceException(ResultEnum.USER_DELETE_ERROR);
        }
    }

    @Transactional
    public void changePowerStatus(Integer powerId) {
        Power power = powerService.findByPowerId(powerId);
        if (power == null) {
            log.error("【更改权限状态】权限不存在，powerId={}", powerId);
            throw new ServiceException(ResultEnum.POWER_NOT_EXIST);
        }
        power.setPowerStatus(!power.getPowerStatus());
        int rows = powerService.updatePower(power);
        if (rows == 0) {
            log.error("【更改权限状态】更改角权限状态失败，powerId={}", powerId);
            throw new ServiceException(ResultEnum.CHANGE_POWER_STATUS_ERROR);
        }
    }

    @Transactional
    public PowerVO editPower(PowerEditForm powerEditForm) {
        Power power = powerService.findByPowerId(powerEditForm.getPowerId());
        if (power == null) {
            log.error("【编辑权限】权限不存在");
            throw new ServiceException(ResultEnum.POWER_NOT_EXIST);
        }
        power.setPowerGroup(powerEditForm.getPowerGroup());
        power.setPowerName(powerEditForm.getPowerName());
        power.setPowerPath(powerEditForm.getPowerPath());
        StringBuilder powerAccessMethods = new StringBuilder();
        for (String powerAccessMethod : powerEditForm.getPowerAccessMethodList()) {
            if (powerAccessMethods.toString().equals("")) {
                powerAccessMethods = new StringBuilder(powerAccessMethod);
            } else {
                powerAccessMethods.append("||").append(powerAccessMethod);
            }
        }
        power.setPowerAccessMethod(powerAccessMethods.toString());
        int rows = powerService.updatePower(power);
        if (rows == 0) {
            log.error("【编辑权限】编辑权限失败，powerId={}", powerEditForm.getPowerId());
            throw new ServiceException(ResultEnum.POWER_EDIT_ERROR);
        }
        PowerVO powerVO = new PowerVO();
        BeanUtils.copyProperties(power, powerVO);
        return powerVO;
    }

    public List<RolePowerGroupVO> rolePowerList(Integer roleId) {
        List<RolePowerGroupVO> rolePowerGroupVOS = new ArrayList<>();
        Role role = roleService.findByRoleId(roleId);
        if (role == null) {
            log.error("【角色权限列表】角色不存在");
            throw new ServiceException(ResultEnum.ROLE_NOT_EXIST);
        }
        List<String> rolePowers = new ArrayList<>();
        if (role.getRolePowers() != null) {
            rolePowers = Arrays.asList(role.getRolePowers().split("\\|\\|"));
        }
        List<Power> powers = powerService.findAllPower();
        List<String> powerGroups = powers.stream().map(Power::getPowerGroup).collect(Collectors.toList());
        powerGroups = powerGroups.stream().distinct().collect(Collectors.toList());
        for (String powerGroup : powerGroups) {
            RolePowerGroupVO rolePowerGroupVO = new RolePowerGroupVO();
            rolePowerGroupVO.setPowerGroup(powerGroup);
            List<Power> powerList = powers.stream().filter(e -> e.getPowerGroup().equals(powerGroup)).collect(Collectors.toList());
            List<RolePowerVO> rolePowerVOS = new ArrayList<>();
            for (Power power : powerList) {
                RolePowerVO rolePowerVO = new RolePowerVO();
                BeanUtils.copyProperties(power, rolePowerVO);
                List<String> rolePowerList = rolePowers.stream().filter(e -> e.equals(power.getPowerName())).collect(Collectors.toList());
                if (rolePowerList.size() == 0) {
                    rolePowerVO.setIsEnable(false);
                } else {
                    rolePowerVO.setIsEnable(true);
                }
                rolePowerVOS.add(rolePowerVO);
            }
            rolePowerGroupVO.setRolePowerVOS(rolePowerVOS);
            rolePowerGroupVOS.add(rolePowerGroupVO);
        }
        return rolePowerGroupVOS;
    }

    public List<UserPowerGroupVO> userPowerList(Integer userId) {
        List<UserPowerGroupVO> userPowerGroupVOS = new ArrayList<>();
        User user = userService.findByUserId(userId);
        if (user == null) {
            log.error("【用户权限列表】用户不存在");
            throw new ServiceException(ResultEnum.USER_NOT_EXIST);
        }
        List<String> userPowers = new ArrayList<>();
        if (user.getUserPowers() != null) {
            userPowers = Arrays.asList(user.getUserPowers().split("\\|\\|"));
        }
        List<Power> powers = powerService.findAllPower();
        List<String> powerGroups = powers.stream().map(Power::getPowerGroup).collect(Collectors.toList());
        powerGroups = powerGroups.stream().distinct().collect(Collectors.toList());
        for (String powerGroup : powerGroups) {
            UserPowerGroupVO userPowerGroupVO = new UserPowerGroupVO();
            userPowerGroupVO.setPowerGroup(powerGroup);
            List<Power> powerList = powers.stream().filter(e -> e.getPowerGroup().equals(powerGroup)).collect(Collectors.toList());
            List<UserPowerVO> userPowerVOS = new ArrayList<>();
            for (Power power : powerList) {
                UserPowerVO userPowerVO = new UserPowerVO();
                BeanUtils.copyProperties(power, userPowerVO);
                List<String> userPowerList = userPowers.stream().filter(e -> e.equals(power.getPowerName())).collect(Collectors.toList());
                if (userPowerList.size() == 0) {
                    userPowerVO.setIsEnable(false);
                } else {
                    userPowerVO.setIsEnable(true);
                }
                userPowerVOS.add(userPowerVO);
            }
            userPowerGroupVO.setUserPowerVOS(userPowerVOS);
            userPowerGroupVOS.add(userPowerGroupVO);
        }
        return userPowerGroupVOS;
    }
}
